﻿namespace MetaProperties.Core
{
    using System;

    using MetaProperties.Framework;

    /// <summary>
    /// An event filter which catches unhandled exceptions from events for
    /// handling elsewhere.
    /// </summary>
    public class IsolatingEventFilter
    {
        /// <summary>
        /// Occurs when an event handler throws an exception.
        /// </summary>
        public static event UnhandledEventHandlerExceptionEventHandler UnhandledEventHandlerException;

        /// <summary>
        /// Gets a value indicating whether anything is subscribed to the UnhandledEventHandlerException event.
        /// </summary>
        /// <value><c>true</c> if this something has subscribed to the UnhandledEventHandlerException event; otherwise, <c>false</c>.</value>
        public static bool IsActive
        {
            get { return UnhandledEventHandlerException != null; }
        }

        /////// <summary>
        /////// Gets or sets the MetaProperty configuration.
        /////// </summary>
        /////// <value>The MetaProperty configuration.</value>
        ////private MetaPropertyConfiguration MetaPropertyConfiguration
        ////{
        ////    get;
        ////    set;
        ////}

        /// <summary>
        /// Attempts to handle the given exception.
        /// </summary>
        /// <param name="t">The exception.</param>
        /// <returns><c>true</c> if the exception has handled; <c>false</c> otherwise.</returns>
        public static bool HandleException(Exception t)
        {
            var handler = UnhandledEventHandlerException;
            if (handler != null)
            {
                handler(null, t);
                return true;
            }

            return false;
        }
        
        /////// <summary>
        /////// Sets the MetaProperty configuration.
        /////// </summary>
        /////// <param name="configuration">The configuration.</param>
        ////public void SetMetaPropertyConfiguration(MetaPropertyConfiguration configuration)
        ////{
        ////    this.MetaPropertyConfiguration = configuration;
        ////}

        /////// <summary>
        /////// Performs filtering of the event.
        /////// </summary>
        /////// <param name="sender">The sender.</param>
        /////// <param name="args">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /////// <param name="pipeline">The pipeline.</param>
        ////public void PerformFilter(object sender, EventArgs args, IFilterPipeline pipeline)
        ////{
        ////    try
        ////    {
        ////        pipeline.Resume(sender, args);
        ////    }
        ////    catch (Exception t)
        ////    {
        ////        if (!HandleException(t))
        ////        {
        ////            throw;
        ////        }
        ////    }
        ////}
    }
}
